<template>
    <div class="home">
        <div class="box">
            <div class="left">
                <div class="userdata">
                    <div class="header">
                        <div class="img">
                            <img v-if="userdata.imgUrl" :src="userdata.imgUrl" alt="">
                        </div>
                        <div class="name">
                            <p>{{ userdata.account }}</p>
                            <div class="opt">管理员</div>
                        </div>
                    </div>
                    <div class="bottom">
                        <p>登录时间: <span>{{ userdata.loginTime }}</span></p>
                    </div>
                </div>
                <div class="language">
                    <div ref="language" style="width: 100%;height: 300px;"></div>
                </div>
            </div>
            <div class="right">
                <div class="right-header">
                    <div class="box">
                        <div class="left2">
                            <i class="el-icon-tickets"></i>
                        </div>
                        <div class="right2">
                            <p ref="articleTotal">{{ articleTotal || 0 }}</p>
                            <div class="num">文章数量</div>
                        </div>
                    </div>
                    <div class="box">
                        <div class="left2">
                            <i class="el-icon-chat-dot-square"></i>
                        </div>
                        <div class="right2">
                            <p ref="commentTotal">{{ commentTotal || 0 }}</p>
                            <div class="num">评论数量</div>
                        </div>
                    </div>
                    <div class="box">
                        <div class="left2">
                            <i class="el-icon-user"></i>
                        </div>
                        <div class="right2">
                            <p ref="userTotal">{{ userTotal || 0 }}</p>
                            <div class="num">用户数量</div>
                        </div>
                    </div>
                </div>
                <div class="content">
                    <div class="p" ref="barElement" style="width: 48%;height:300px;"></div>
                    <div class="p" ref="pieElement" style="width: 48%;height:300px;"></div>
                    <div class="p" ref="commentElement" style="width: 100%;height:300px;"></div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import * as echarts from 'echarts';
import { gsap } from "gsap"
import { listArticle, detail2, listUser, itemsArticleComment, itemsNoteComment, listWish, itemsMsg, host } from '@/api/index'
export default {
    data() {
        return {
            // 用户数据
            userdata: {},
            // 语言数据
            languageData: [
                { name: 'Vue', percnet: '87.98' },
                { name: 'Javascript', percnet: '10.95' },
                { name: 'HTML', percnet: '0.28' },
                { name: 'CSS', percnet: '0.70' },
                { name: 'Less', percnet: '0.08' },
            ],
            // 文章总数
            articleTotal: 0,
            // 文章数据
            articleArr: [],

            // 用户数量
            userTotal: 0,
            // 用户性别比例
            userSex: [
                // { name: '男生', value: 335 }
            ],

            // 评论总数
            commentTotal: 0,
            // 评论数据
            commentArr: [],

            articleTween: null,
            commentTween: null,
            userTween: null,

            // echart颜色
            color: ['#409EFF', '#64D772', '#40C9C6']
        }
    },
    mounted() {
        this.$nextTick(() => {
            let language = this.$refs.language;
            if (language) {
                let myChart3 = echarts.init(language);
                myChart3.setOption({
                    title: {
                        text: '代码比例',
                    },
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow'
                        }
                    },
                    xAxis: {
                        type: 'value',
                        show: false
                    },
                    yAxis: {
                        type: 'category',
                        data: this.languageData.map(item => item.name),
                        axisLabel: {
                            color: '#666',
                            fontSize: 14
                        }
                    },
                    series: [
                        {
                            name: '代码比例',
                            type: 'bar',
                            barWidth: '50%',
                            label: {
                                show: true,
                                position: 'right',
                                formatter: '{c}%',
                                color: '#666'
                            },
                            data: this.languageData.map((item, index) => ({
                                value: item.percnet,
                                name: item.name,
                                itemStyle: {
                                    color: this.color[index % this.color.length]
                                }
                            }))
                        }
                    ],
                    grid: {
                        left: '5%',
                        right: '5%',
                        bottom: '5%',
                        containLabel: true
                    },
                    color: ['#409EFF', '#F56C6C', '#67C23A']
                })

            }

        })

    },
    async created() {
        // console.log(this.$store.state.userData);
        // this.userdata = this.$store.state.userData
        // console.log(this.userdata);
        await this.detail2Fn()
        await this.listArticleFn()
        await this.listUserFn()
        const result1 = await this.itemsArticleCommentFn()
        const result2 = await this.itemsNoteCommentFn()
        const result3 = await this.itemsMsgFn()
        const result4 = await this.listWishFn()
        this.commentTotal = result1.total + result2.total + result3.total + result4.total
        this.commentArr = [result3, result1, result4, result2]
        if (this.commentArr.length > 0) {
            await this.commentChart()
            await this.animateNumbers()

        }
        // console.log('11111', this.commentArr);

    },
    watch: {
        $route: {
            immediate: true,
            deep: true,
            handler(newRoute) {
                // console.log('111', newRoute);
                this.$store.commit("addTab", newRoute);
            }
        }
    },
    // 组件销毁前清理动画
    beforeDestroy() {
        // 清理所有正在进行的动画
        if (this.articleTween) {
            this.articleTween.kill();
        }
        if (this.commentTween) {
            this.commentTween.kill();
        }
        if (this.userTween) {
            this.userTween.kill();
        }
    },


    methods: {

        async detail2Fn() {
            let token = localStorage.getItem('AUTO_TOKEN')
            await detail2({ token })
                .then(
                    res => {
                        // console.log(res)
                        if (res.code == 200) {
                            this.userdata = res.result.map(item => {
                                return {
                                    username: item.username,
                                    account: item.account,
                                    imgUrl: host + item.imgUrl
                                }
                            })[0]
                        }
                        this.userdata.loginTime = this.$store.state.userData.loginTime
                        // console.log(this.userdata)
                    }, err => {
                        console.log(err)
                    }
                )
        },
        // 使用 gsap 实现数字渐变动画
        animateNumbers() {
            // 确保所有数据都已加载
            if (!this.articleTotal || !this.commentTotal || !this.userTotal) {
                return
            }

            // 清理之前的动画（如果有的话）
            if (this.articleTween) {
                this.articleTween.kill();
            }
            if (this.commentTween) {
                this.commentTween.kill();
            }
            if (this.userTween) {
                this.userTween.kill();
            }

            // 设置初始值为0
            this.$refs.articleTotal.textContent = '0'
            this.$refs.commentTotal.textContent = '0'
            this.$refs.userTotal.textContent = '0'
            // 文章数量动画
            this.articleTween = gsap.to(this.$refs.articleTotal, {
                duration: 1.5, // 动画持续时间
                textContent: this.articleTotal, // 动画的目标值
                ease: "power1.out", // 控制动画的速度曲线，这里表示先快后慢的减速效
                snap: { textContent: 1 }, // 确保显示的数字始终是整数，不会有小数点
                onUpdate: () => {  //在动画每一帧更新时执行的回调函数
                    this.$refs.articleTotal.textContent = Math.floor(this.$refs.articleTotal.textContent)
                }
            })

            // 评论数量动画
            this.commentTween = gsap.to(this.$refs.commentTotal, {
                duration: 1.5,
                textContent: this.commentTotal,
                ease: "power1.out",
                snap: { textContent: 1 },
                onUpdate: () => {
                    this.$refs.commentTotal.textContent = Math.floor(this.$refs.commentTotal.textContent)
                }
            })

            // 用户数量动画
            this.userTween = gsap.to(this.$refs.userTotal, {
                duration: 1.5,
                textContent: this.userTotal,
                ease: "power1.out",
                snap: { textContent: 1 },
                onUpdate: () => {
                    this.$refs.userTotal.textContent = Math.floor(this.$refs.userTotal.textContent)
                }
            })
        },

        // 评论echarts图
        commentChart() {
            let myChart = echarts.getInstanceByDom(this.$refs.commentElement);
            if (!myChart) {
                myChart = echarts.init(this.$refs.commentElement);
            }
            const option = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '5%',
                    top: '8%',
                    containLabel: true
                },
                xAxis: {
                    type: 'value',

                },
                yAxis: {
                    type: 'category',
                    data: this.commentArr.map(item => item.name)

                },
                series: [
                    {
                        data: this.commentArr.map((item, index) => {
                            return {
                                value: item.total,
                                itemStyle: {
                                    color: this.color[index % this.color.length]
                                }
                            }
                        }),
                        type: 'bar'
                    }
                ]
            };
            myChart.setOption(option, true);
        },

        async itemsArticleCommentFn() {
            const result = await itemsArticleComment({ page_num: 1, page_size: 5 })
            // console.log(result)
            let total = '';
            if (result.code == 200) {
                total = result.total
            }
            return {
                total,
                name: '文章评论',
            }
        },
        async itemsNoteCommentFn() {
            const result = await itemsNoteComment({ page_num: 1, page_size: 5 })
            // console.log(result)
            let total = '';
            if (result.code == 200) {
                total = result.total
            }
            return {
                total,
                name: '随笔评论',
            }
        },
        async listWishFn() {
            const result = await listWish({ page_num: 1, page_size: 5 })
            // console.log(result)
            let total = '';
            if (result.code == 200) {
                total = result.total
            }
            return {
                total,
                name: '祝福评论',
            }
        },
        async itemsMsgFn() {
            const result = await itemsMsg({ page_num: 1, page_size: 5 })
            // console.log(result)
            let total = '';
            if (result.code == 200) {
                total = result.total
            }
            return {
                total,
                name: '弹幕留言',
            }
        },


        // 用户数据的echarts图
        userChart() {
            let myChart = echarts.getInstanceByDom(this.$refs.pieElement);
            if (!myChart) {
                myChart = echarts.init(this.$refs.pieElement);
            }
            const option = {
                tooltip: {
                    trigger: 'item'
                },
                legend: {
                    top: '5%',
                    left: 'center'
                },
                series: [
                    {
                        name: '性别',
                        type: 'pie',
                        radius: ['40%', '70%'],
                        avoidLabelOverlap: false,
                        itemStyle: {
                            borderRadius: 10,
                            borderColor: '#fff',
                            borderWidth: 2
                        },
                        label: {
                            show: false,
                            position: 'center'
                        },
                        emphasis: {
                            label: {
                                show: true,
                                fontSize: 40,
                                fontWeight: 'bold'
                            }
                        },
                        labelLine: {
                            show: false
                        },
                        data: this.userSex.map((item, index) => {
                            return {
                                value: item.value,
                                name: item.name,
                                itemStyle: {
                                    color: this.color[index % this.color.length]
                                }

                            }
                        })
                    }
                ]
            };
            myChart.setOption(option, true);
        },

        // 文章数据的echarts图
        updateBarChart() {
            let myChart = echarts.getInstanceByDom(this.$refs.barElement);
            if (!myChart) {
                myChart = echarts.init(this.$refs.barElement);
            }
            const option = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                grid: {
                    left: '5%',
                    right: '5%',
                    bottom: '3%',
                    top: '10%',
                    containLabel: true
                },
                xAxis: [
                    {
                        type: 'category',
                        data: this.articleArr.map(item => item.title),
                        axisTick: {
                            alignWithLabel: true
                        }
                    }
                ],
                yAxis: [
                    {
                        type: 'value'
                    }
                ],
                series: [
                    {
                        name: '数量',
                        type: 'bar',
                        barWidth: '60%',
                        data: this.articleArr.map((item, index) => {
                            return {
                                value: item.total,
                                itemStyle: {
                                    color: this.color[index % this.color.length]
                                }
                            }
                        })
                    }
                ]
            };
            myChart.setOption(option, true); // 使用 true 参数表示不合并原有配置
        },

        async listArticleFn() {
            await listArticle().then(
                res => {
                    // console.log(res)
                    if (res.code == 200) {
                        this.articleTotal = res.total
                        let arr = [...new Set(res.result.map(item => item.cate))]
                        // console.log(arr)
                        this.articleArr = arr.map(item => {
                            return {
                                title: item,
                                total: res.result.filter(i => i.cate == item).length
                            }
                        })
                        // 在数据获取成功后，更新或初始化图表
                        this.$nextTick(async () => {
                            await this.updateBarChart(); // 更新柱状图

                        });
                    }
                }, err => {
                    console.log(err)
                }
            )
        },
        async listUserFn() {
            await listUser().then(
                res => {
                    // console.log(res)
                    if (res.code == 200) {
                        this.userTotal = res.total
                        let arr = [...new Set(res.result.map(item => item.gender))]
                        // console.log(arr)
                        this.userSex = arr.map(item => {
                            return {
                                name: item && item !== 'null' && item !== 'undefined' ? item : '未知',
                                value: res.result.filter(i => i.gender == item).length
                            };
                        })
                        // console.log(this.userSex)
                        // 在数据获取成功后，更新或初始化图表
                        this.$nextTick(() => {
                            this.userChart()
                        });
                    }
                }, err => {
                    console.log(err)
                }
            )
        },

    }

}

</script>

<style lang="less" scoped>
@import "@/assets/style/variables.less";

.home {
    width: 100%;
    height: 100%;
    min-height: 800px;
    background-color: #fff;
    border-radius: @border-radius;
    box-shadow: @box-shadow;
    padding: @padd;

    .box {
        display: flex;
        width: 100%;
        height: 100%;

        .left {
            width: calc(30% + 20px);
            height: 100%;
            padding-right: 20px;
            border-right: 1px solid #e1e0e0;

            .userdata {
                width: 100%;
                padding: 20px;
                border-radius: @border-radius;
                box-shadow: 0 0 10px rgba(0, 0, 0, .1);

                .header {
                    display: flex;
                    align-items: center;
                    padding-bottom: 20px;
                    border-bottom: 1px solid #ccc;

                    .img {
                        width: 100px;
                        height: 100px;
                        border-radius: 50%;
                        overflow: hidden;

                        img {
                            width: 100%;
                            height: 100%;
                        }
                    }

                    .name {
                        margin-left: 50px;

                        p {
                            font-size: 20px;
                            color: #000;
                        }

                        .opt {
                            font-size: 12px;
                            color: #969595;
                        }
                    }

                }

                .bottom {
                    padding: 20px 0 0px;
                    color: #969595;
                    font-size: 14px;

                    span {
                        margin-left: 60px;
                    }
                }
            }

            .language {
                margin-top: 20px;
                width: 100%;
                border-radius: @border-radius;
                box-shadow: 0 0 10px rgba(0, 0, 0, .1);
            }
        }

        .right {
            width: calc(100% - 30% - 20px);
            // display: flex;
            margin-left: 20px;
            height: 100%;

            .right-header {
                height: auto;
                width: 100%;
                display: flex;
                height: 100px;
                justify-content: space-between;

                // 第一个 box 的 left2
                .box:nth-child(1) .left2 {
                    background-color: #409EFF;
                }

                // 第二个 box 的 left2
                .box:nth-child(2) .left2 {
                    background-color: #64D772;
                }

                // 第三个 box 的 left2
                .box:nth-child(3) .left2 {
                    background-color: #40C9C6;
                }

                .box:nth-child(1) .right2 {
                    p {
                        color: #409EFF;
                    }
                }

                .box:nth-child(2) .right2 {
                    p {
                        color: #64D772;
                    }
                }

                .box:nth-child(3) .right2 {
                    p {
                        color: #40C9C6;
                    }
                }

                .box {
                    width: calc(97% / 3);
                    display: flex;
                    align-items: center;
                    height: 100%;
                    border-radius: 5px;
                    box-shadow: 0 0 10px rgba(0, 0, 0, .1);
                    overflow: hidden;


                    .left2 {
                        width: 40%;
                        height: 100%;
                        background-color: #409EFF;
                        display: flex;
                        align-items: center;
                        justify-content: center;



                        i {
                            display: block;
                            line-height: 50px;
                            font-size: 50px;
                            color: #fff;
                        }
                    }

                    .right2 {
                        width: 60%;
                        text-align: center;

                        p {
                            font-size: 20px;
                            font-weight: bold;
                        }

                        .num {
                            color: #969595;
                            margin-top: 10px;
                            font-size: 14px;
                        }
                    }
                }
            }

            .content {
                width: 100%;
                margin-top: 30px;
                display: flex;
                justify-content: space-between;
                flex-wrap: wrap;

                .p {
                    border-radius: @border-radius;
                    box-shadow: 0 0 10px rgba(0, 0, 0, .1);
                    margin-bottom: 20px;
                }
            }
        }
    }
}
</style>